package com.quan.bookmall.controller;

import com.quan.bookmall.dto.UserDTO;
import com.quan.bookmall.dto.request.LoginRequest;
import com.quan.bookmall.dto.request.RegisterRequest;
import com.quan.bookmall.dto.response.ApiResponse;
import com.quan.bookmall.dto.response.JwtResponse;
import com.quan.bookmall.entity.User;
import com.quan.bookmall.security.JwtUtils;
import com.quan.bookmall.security.UserDetailsImpl;
import com.quan.bookmall.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final AuthenticationManager authenticationManager;
    private final UserService userService;
    private final JwtUtils jwtUtils;
    
    @PostMapping("/login")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            // 先检查用户是否存在以及状态
            UserDTO user = userService.findByUsername(loginRequest.getUsername());
            if (user != null && user.getStatus() == 0) {
                return ResponseEntity.badRequest().body(ApiResponse.error("您的账号已被禁用，请联系管理员"));
            }
            
            // 验证用户名密码
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
            
            // 设置认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 生成JWT
            String jwt = jwtUtils.generateJwtToken(authentication);
            
            // 获取用户详情
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            
            // 返回JWT和用户信息
            return ResponseEntity.ok(ApiResponse.success(new JwtResponse(
                    jwt,
                    userDetails.getId(),
                    userDetails.getUsername(),
                    userDetails.getEmail(),
                    userDetails.getAuthorities().iterator().next().getAuthority().replace("ROLE_", "")
            )));
        } catch (Exception e) {
            // 如果是认证异常，让全局异常处理器处理
            throw e;
        }
    }
    
    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@Valid @RequestBody RegisterRequest registerRequest) {
        // 验证用户名是否已存在
        if (userService.existsByUsername(registerRequest.getUsername())) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户名已被使用"));
        }
        
        // 验证邮箱是否已存在
        if (userService.existsByEmail(registerRequest.getEmail())) {
            return ResponseEntity.badRequest().body(ApiResponse.error("邮箱已被使用"));
        }
        
        // 验证两次密码是否一致
        if (!registerRequest.getPassword().equals(registerRequest.getConfirmPassword())) {
            return ResponseEntity.badRequest().body(ApiResponse.error("两次输入的密码不一致"));
        }
        
        // 注册用户
        userService.register(registerRequest);
        
        return ResponseEntity.ok(ApiResponse.success("用户注册成功"));
    }
} 